import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import Cookies from 'js-cookie'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 180000 // request timeout
})

const CancelToken = axios.CancelToken
const source = CancelToken.source()
const controller = new AbortController()

// request interc50eptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // const req = new XMLHttpRequest()
    // var xx = req.getResponseHeader('x-powered-by')
    // console.log(req)
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }

    config.params = { cancelToken: source.token, signal: controller.signal }
    return config
  },
  error => {
    // do something with request error
    console.log('request error', error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // console.log('response', response)
    const accesstoken = response.headers['access-token']
    if (accesstoken) {
      setToken(accesstoken)
    }
    const res = response.data
    // if the custom code is not 20000, it is judged as an error. statusCode !== 200
    if (res.statusCode !== 200) {
      source.cancel('Operation canceled by the error')
      controller.abort()
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;  || res.statusCode === 500
      if (res.statusCode === 401) {
        // to re-login
        MessageBox.confirm('登录过期，请重新登录', '提示', {
          confirmButtonText: '重新登陆',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/logout').then(() => {
            location.reload()
          })
        }).catch(() => {
          console.log('mistake')
        })
      } else {
        Message({
          message: res.statusCode + res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error(res.errors || 'Error'))
    } else {
      return res
    }
  },
  error => {
    // console.info('response error') // for debug
    console.log(error.response)

    switch (error.response.status) {
      case 401:
        MessageBox.confirm(error.response.statusText, '提示', {
          confirmButtonText: '重新登陆',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          removeToken() // must remove  token  first
          Cookies.remove('permission')
          Cookies.remove('userId')
          window.location.reload() // f5
          resetRouter()
        })
        break

      default:
        MessageBox.confirm(error.response.status + ': ' + error.response.statusText + ', ' + error.response.data.title, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
    }

    return Promise.reject(error)
  }
)

export { service, CancelToken, source }
